﻿<%@ WebHandler Language="C#" Class="OfferPriceHandler" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using StarTech.DBUtility;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Web.DynamicData;


public class OfferPriceHandler : IHttpHandler
{
    AdoHelper ado = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);

            string goodsId = Common.NullToEmpty(context.Request["goodsId"]);
            string orderId = Common.NullToEmpty(context.Request["orderId"]);
            string info = Common.NullToEmpty(context.Request["info"]);
            string id = Common.NullToEmpty(context.Request["id"]);
            string isPub = Common.NullToEmpty(context.Request["isPub"]);
            string words = Common.NullToEmpty(context.Request["words"]);
            string stars = Common.NullToEmpty(context.Request["stars"]);
            bool evalWorker = Common.NullToEmpty(context.Request["evalWorker"]) == "1";

            string mid = Common.NullToEmpty(context.Request["mid"]);
            mid = string.IsNullOrEmpty(mid) ? memberId : mid;

            switch (flag.ToLower())
            {
                case "getinfo":
                    context.Response.Write(GetInfo(goodsId, orderId, mid));
                    break;
                case "complete":
                    context.Response.Write(CompleteJob(goodsId, orderId, info));
                    break;
                case "delpic":
                    context.Response.Write(DeletePic(id));
                    break;
                case "upload":
                    if (context.Request.Files.Count == 0)
                    {
                        context.Response.Write("请上传文件");  //代表文件为空
                    }
                    else
                    {
                        context.Response.Write(UploadFile(context.Request.Files[0], goodsId, orderId));
                    }
                    break;
                case "finish":
                    context.Response.Write(Finish(orderId));
                    break;
                case "userinfo":
                    context.Response.Write(UserInfo(orderId, evalWorker));
                    break;
                case "comment":
                    context.Response.Write(Comment(orderId, goodsId, isPub, words, stars, evalWorker));
                    break;
                case "getwords":
                    context.Response.Write(GetWords());
                    break;
            }
        }
    }

    private string GetWords()
    {
        string strSql = @"select * from T_Base_CommentWords";
        return JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql).Tables[0]);
    }

    private string UserInfo(string orderId, bool evalWorker)
    {
        string workerId = Common.GetWorkerIdByOrderId(orderId);
        string bossId = Common.GetBossIdByOrderId(orderId);
        string strSql = @"select MemberId,TrueName,Mobile,AddressDetail,HeadImg,LevelName from T_Member_Info where MemberId=@MemberId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@MemberId",evalWorker?workerId:bossId)
        };
        return JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
    }

    private string Comment(string orderId, string goodsId, string isPub, string words, string stars, bool evalWorker)
    {
        int result = 0;
        string strSql = @"select * from T_Order_Comment where orderId=@OrderId and createMemberId=@createMemberId";
        SqlParameter[] p = new SqlParameter[]
        {
            new SqlParameter("@orderId", orderId),
            new SqlParameter("@createMemberId", memberId),
        };
        if (ado.ExecuteSqlDataset(strSql, p).Tables[0].Rows.Count == 0)
        {
            string commentId = Guid.NewGuid().ToString();
            string workerId = Common.GetWorkerIdByOrderId(orderId);
            string bossId = Common.GetBossIdByOrderId(orderId);
            strSql = @"insert into T_Order_Comment(commentId, goodsId, orderid,memberid, createMemberId, commentType, isShow, context,isWorker,createTime)
                values(@commentId, @goodsId, @orderid,@memberid, @createMemberId, @commentType, @isShow, @context,@isWorker,getdate())";
            SqlParameter[] p1 = new SqlParameter[]
            {
                new SqlParameter("@commentId", commentId),
                new SqlParameter("@goodsId", goodsId),
                new SqlParameter("@orderid", orderId),
                new SqlParameter("@memberid", evalWorker?workerId:bossId),
                new SqlParameter("@createMemberId", memberId),
                new SqlParameter("@commentType", stars),
                new SqlParameter("@isShow", isPub.Equals("1")?"1":"0"),
                new SqlParameter("@context", words),
                new SqlParameter("@isWorker", evalWorker?"1":"0"),
            };
            result = ado.ExecuteSqlNonQuery(strSql, p1);

            string GoodsName = Common.GetGoodsNameByOrderId(orderId);
            string jobType = Common.GetJobTypeByGoodsId(goodsId);
            if (evalWorker)
            { Common.AddLogMsg(workerId, "雇主评价", "【" + GoodsName + "】任务雇主已评价<br />内容(" + stars + "星)：" + words, "Task" + (jobType == "DG" ? "People" : "") + "Info.html?gid=" + goodsId, 0); }
            else
            { Common.AddLogMsg(bossId, "雇员评价", "【" + GoodsName + "】任务雇员已评价<br />内容(" + stars + "星)：" + words, "MyTask" + (jobType == "DG" ? "People" : "") + "Info.html?gid=" + goodsId, 0); }
        }
        else
        {
            string commentId = Guid.NewGuid().ToString();
            strSql = @"update T_Order_Comment set " + (isPub.Equals("1") ? "isShow='1'," : "") + "context=@context,commentType=@commentType where orderId=@OrderId and memberId=@memberId";
            SqlParameter[] p1 = new SqlParameter[]
            {
                new SqlParameter("@OrderId", orderId),
                new SqlParameter("@memberId", memberId),
                new SqlParameter("@commentType", stars),
                new SqlParameter("@context", words),
            };
            result = ado.ExecuteSqlNonQuery(strSql, p1);
        }

        strSql = @"select count(1) from t_order_info 
            where (IsComplete='0' or IsComplete is null) and OrderId in 
            (select OrderId from T_Order_InfoDetail where GoodsId in 
            (select GoodsId from T_Order_InfoDetail where OrderId=@orderId))";
        SqlParameter[] p3 = new SqlParameter[]
        {
            new SqlParameter("@orderId", orderId),
        };
        if (result == 1 && Convert.ToInt32(ado.ExecuteSqlScalar(strSql, p3)) == 0)
        {
            SqlParameter[] p1 = new SqlParameter[]
            {
                new SqlParameter("@goodsId", goodsId),
            };
            ado.ExecuteSqlNonQuery("update T_Goods_Info set JobStatus='已结束' where goodsId=@goodsId", p1);

        }
        return result.ToString();
    }

    private string Finish(string orderId)
    {
        string strSql = @"update T_Order_Info set iscomplete='1' where orderId=@orderId;";
        SqlParameter[] p = new SqlParameter[]
        {
            new SqlParameter("@orderId", orderId),
        };
        string result = ado.ExecuteSqlNonQuery(strSql, p).ToString();

        strSql = @"select count(1) from t_order_info where (IsComplete='0' or IsComplete is null) and OrderId in 
            (select OrderId from T_Order_InfoDetail where GoodsId in 
            (select GoodsId from T_Order_InfoDetail where OrderId=@orderId))";
        SqlParameter[] p2 = new SqlParameter[]
        {
            new SqlParameter("@orderId", orderId),
        };

        if (Convert.ToInt32(ado.ExecuteSqlScalar(strSql, p2)) == 0)
        {
            strSql = "update T_Goods_Info set JobStatus='已完成' where goodsId in (select goodsId from T_Order_InfoDetail where orderId=@orderId);";
            SqlParameter[] p3 = new SqlParameter[]
            {
                new SqlParameter("@orderId", orderId),
            };
            ado.ExecuteSqlScalar(strSql, p3);
        }

        string mId = Common.GetWorkerIdByOrderId(orderId);
        string GoodsName = Common.GetGoodsNameByOrderId(orderId);
        string TrueName = Common.GetBossNameByOrderId(orderId);

        SqlParameter[] p4 = new SqlParameter[]
        {
            new SqlParameter("@orderId", orderId),
        };
        strSql = "select * from T_Member_CompleteJob where OrderId=@OrderId";
        DataTable dt = ado.ExecuteSqlDataset(strSql, p4).Tables[0];
        string gid = "", mid = "";
        if (dt.Rows.Count > 0)
        {
            gid = Common.NullToEmpty(dt.Rows[0]["GoodsId"]);
            mid = Common.NullToEmpty(dt.Rows[0]["MemberId"]);
        }
        Common.AddLogMsg(mId, "任务验收", "【" + GoodsName + "】任务，雇主 " + TrueName + " 已验收", "Finished.html?isback=1&gid=" + gid + "&mid=" + mid + "&oid=" + orderId, 0);
        //系统支付费用到用户账户里
        object objMoney = ado.ExecuteSqlScalar("select OrderAllMoney from T_Order_Info where orderId='" + orderId + "'");
        MoneyBagTools.CreateMoneyBagDetail(mId, (objMoney == null ? 0 : decimal.Parse(objMoney.ToString())), "cz", orderId);
        return result;
    }

    private string GetInfo(string goodsId, string orderId, string mid)
    {
        string json = "";
        string strSql = @"select * from T_Member_CompleteJob where GoodsId=@GoodsId and OrderId=@OrderId and MemberId=@MemberId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@MemberId",mid),
            new SqlParameter("@GoodsId",goodsId),
            new SqlParameter("@OrderId",orderId),
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);
        json += "_$$_";
        string strSql2 = @"select sysnumber,picPath from T_Goods_Pic where GoodsId=@GoodsId and MemberId=@MemberId and OrderId=@OrderId and PicType='WG' order by orderby";
        SqlParameter[] p2 = new SqlParameter[] {
            new SqlParameter("@MemberId",mid),
            new SqlParameter("@GoodsId",goodsId),
            new SqlParameter("@OrderId",orderId),
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql2, p2).Tables[0]);
        return json;
    }

    private string CompleteJob(string goodsId, string orderId, string info)
    {

        string strSql = @"select * from T_Member_CompleteJob where GoodsId=@GoodsId and OrderId=@OrderId and MemberId=@MemberId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@MemberId",memberId),
            new SqlParameter("@GoodsId",goodsId),
            new SqlParameter("@OrderId",orderId),
        };

        if (ado.ExecuteSqlDataset(strSql, p).Tables[0].Rows.Count == 0)
        {
            string mId = Common.GetBossIdByGoodsId(goodsId);
            string GoodsName = Common.GetGoodsNameByGoodsId(goodsId);
            string TrueName = ado.ExecuteSqlScalar("select top 1 TrueName from T_Member_Info where MemberId='" + memberId + "'").ToString();
            Common.AddLogMsg(mId, "任务完工", "【" + GoodsName + "】任务，雇员 " + TrueName + " 已完工", "FinishedInfo.html?gid=" + goodsId + "&mid=" + memberId + "&oid=" + orderId, 0);

            strSql = @"insert into T_Member_CompleteJob(CompleteId, MemberId, GoodsId,OrderId, CompleteTime, CompleteInfo) values(@CompleteId, @MemberId, @GoodsId,@OrderId, getdate(), @CompleteInfo)";
            SqlParameter[] p1 = new SqlParameter[] {
                new SqlParameter("@CompleteId",Guid.NewGuid().ToString()),
                new SqlParameter("@MemberId",memberId),
                new SqlParameter("@GoodsId",goodsId),
                new SqlParameter("@OrderId",orderId),
                new SqlParameter("@CompleteInfo",info),
            };
            return ado.ExecuteSqlNonQuery(strSql, p1).ToString();
        }
        else
        {
            strSql = @"update T_Member_CompleteJob set CompleteInfo=@CompleteInfo where GoodsId=@GoodsId and OrderId=@OrderId and MemberId=@MemberId";
            SqlParameter[] p1 = new SqlParameter[] {
                new SqlParameter("@MemberId",memberId),
                new SqlParameter("@GoodsId",goodsId),
                new SqlParameter("@OrderId",orderId),
                new SqlParameter("@CompleteInfo",info),
            };
            return ado.ExecuteSqlNonQuery(strSql, p1).ToString();
        }
    }

    private string UploadFile(HttpPostedFile file, string goodsId, string orderId)
    {
        string fileTail = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
        if (fileTail != ".jpeg" && fileTail != ".jpg" && fileTail != ".png" && fileTail != ".bmp" && fileTail != ".gif")
        {
            return "图片格式不正确";
        }
        if (file.ContentLength > 1024000)
        {
            return "图片不能大于1M";
        }

        //保存文件
        string path = "/upload/goods";
        path += "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/";
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
        path += DateTime.Now.ToString("HHmmssffff") + fileTail;
        file.SaveAs(HttpContext.Current.Server.MapPath(path));

        //修改数据库
        string id = Guid.NewGuid().ToString();
        string strSql = string.Format("insert into t_goods_pic(Sysnumber, PicPath, Orderby, PicType,GoodsId,OrderId, MemberId) values(@Sysnumber,@PicPath,@Orderby,@PicType,@GoodsId,@OrderId,@MemberId)");
        SqlParameter[] p = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber",id),
            new SqlParameter("@PicPath",path),
            new SqlParameter("@Orderby","0"),
            new SqlParameter("@PicType","WG"),
            new SqlParameter("@GoodsId",goodsId),
            new SqlParameter("@OrderId",orderId),
            new SqlParameter("@MemberId",memberId),
        };
        ado.ExecuteSqlNonQuery(strSql, p);
        return id + "_$$_" + path;
    }

    private string DeletePic(string id)
    {
        string strSql1 = "select picpath from t_goods_pic where Sysnumber=@Sysnumber and MemberId=@MemberId;";
        SqlParameter[] p1 = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber", id),
            new SqlParameter("@MemberId",memberId),
        };
        string picpath = ado.ExecuteSqlScalar(strSql1, p1).ToString();
        File.Delete(HttpContext.Current.Server.MapPath(picpath));

        string strSql2 = "delete from t_goods_pic where Sysnumber=@Sysnumber and MemberId=@MemberId;";
        SqlParameter[] p2 = new SqlParameter[]
        {
            new SqlParameter("@Sysnumber", id),
            new SqlParameter("@MemberId",memberId),
        };
        return ado.ExecuteSqlNonQuery(strSql2, p2).ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}